//
//  MyShowCameraViewController.m
//  BosidengIphone
//
//  Created by  on 12-1-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MyShowCameraViewController.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MainViewController.h"

@implementation MyShowCameraViewController
@synthesize imageView;
@synthesize takePictureButton;
@synthesize selecFromCameraRollButton;
@synthesize upLoadButton;
@synthesize waitView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [waitView release];
    [imageView release];
    [takePictureButton release];
    [selecFromCameraRollButton release];
    [upLoadButton release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	if (![UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera]) {
		takePictureButton.enabled = NO;
	}
    if (![UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypePhotoLibrary]) {
        selecFromCameraRollButton.enabled = NO;
	}
    upLoadButton.enabled = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    MainViewController *mainView = (MainViewController *)mainViewController;
    mainView.backView.frame = CGRectMake(284, 399, 26, 26);
}

- (void)viewDidDisappear:(BOOL)animated {
    MainViewController *mainView = (MainViewController *)mainViewController;
    mainView.backView.frame = CGRectMake(284, 424, 26, 26);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    self.imageView = nil;
    self.takePictureButton = nil;
    self.selecFromCameraRollButton = nil;
    self.upLoadButton = nil;
    self.waitView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (UIImage *)resizeImage:(UIImage *)sourceImage {
    CGFloat imageWidth = sourceImage.size.width;
    CGFloat imageHeight = sourceImage.size.height;
    CGSize size = CGSizeMake(imageWidth, imageHeight);
    CGFloat width = 640;
    if (imageWidth > width) {
        CGFloat scale = width / size.width;
        size = CGSizeMake(width, size.height * scale);
    }
    NSLog(@"imageSize(%.0f, %.0f), scaleSize(%.0f, %.0f)", imageWidth, imageHeight, size.width, size.height);
	UIGraphicsBeginImageContext(size);
	[sourceImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return image;
}

- (IBAction)upload: (id)sender {
    ASIFormDataRequest *request =[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/ShowAdd.ashx", [AppDelegate serviceUrl]]]];
	//[request setPostValue:@"172.29.129.11" forKey:@"IP"];
	[request setPostValue:[AppDelegate getCustom].customId forKey:@"txt_CustomerID"];
	[request addPostValue:[AppDelegate getLanguage] forKey:@"txt_Language"];
    NSData *data = UIImageJPEGRepresentation([self resizeImage:imageView.image], 1.0);
    [request setData:data forKey:@"ShowPicture"];
    
	[request setTimeOutSeconds:20];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
	[request setShouldContinueWhenAppEntersBackground:YES];
#endif
	[request setDelegate:self];
	[request setDidFailSelector:@selector(uploadFailed:)];
	[request setDidFinishSelector:@selector(uploadFinished:)];
	[requestQueue addOperation:request];
    [waitView startAnimating];
}

- (void)showMessge:(NSString *)message {
    UIAlertView *infoView = [[UIAlertView alloc] 
                             initWithTitle:@""
                             message:message
                             delegate:nil 
                             cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
                             otherButtonTitles:nil];
    [infoView show];
    [infoView release];
}

- (void)uploadFinished:(ASIFormDataRequest *)request {
    [waitView stopAnimating];
	NSString *result = [request responseString];
    //NSLog(@"upload result=%@", result);
    if ([result rangeOfString:@"html"].length > 0
        ||[result rangeOfString:@"xception"].length > 0) {
        upLoadButton.enabled = YES;
		[self showMessge:@"upload Failed!"];
        NSLog(@"upload Failed! result=%@", result);
        return;
    }
	NSArray *resultInfos = [result componentsSeparatedByString:@"|"];
    NSString *resultCode = [resultInfos objectAtIndex:0];
    NSString *resultMessage = [resultInfos objectAtIndex:1];
	if ([@"1" isEqualToString:resultCode]) {
        NSLog(@"upload Success! result=%@", result);
        [self showMessge:resultMessage];
        /*NSString *showId = [resultInfos objectAtIndex:2];
        
        NSString *url = [NSString stringWithFormat:@"%@/GetShow.ashx?showId=%@", [AppDelegate serviceUrl], showId];
        MyShowItemsXmlParser *showParser = [[MyShowItemsXmlParser alloc] init];
        SyncRequestParseOperation *operation = [[SyncRequestParseOperation alloc] initWithURLString:url xmlParser:showParser delegate:self];
        [requestQueue addOperation:operation];
        [operation release];
        [showParser release];*/
	} else {
        upLoadButton.enabled = YES;
		[self showMessge:resultMessage];
        NSLog(@"upload Failed! result=%@", result);
	}
}

- (void)uploadFailed:(ASIFormDataRequest *)request {
    [self showMessge:@"upload Failed!"];
    NSLog(@"upload Failed! error=%@", [request error]);
    [waitView stopAnimating];
	upLoadButton.enabled = YES;
}

- (IBAction)openCamera: (id)sender {
	UIImagePickerController* picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	picker.sourceType = UIImagePickerControllerSourceTypeCamera;
	picker.allowsEditing = YES;
	//picker.showsCameraControls = NO;//关闭默认的摄像设备
	//picker.toolbarHidden = YES;
	
	//设定图像缩放比例
	//picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, 1.0, 1.0);
	
	//[(MainViewController *)mainViewController pushViewController:picker];
	[mainViewController presentModalViewController:picker animated:YES];
	
	[picker release];
}

- (IBAction)openPhotoLibrary: (id)sender {
    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[(MainViewController *)mainViewController pushViewController:picker];
    [mainViewController presentModalViewController:picker animated:YES];
    [picker release];
}

- (UIImage *)cropImage:(UIImage *)image to:(CGRect)cropRect andScaleTo:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGImageRef subImage = CGImageCreateWithImageInRect([image CGImage], cropRect);
    CGRect myRect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    CGContextScaleCTM(context, 1.0f, -1.0f);
    CGContextTranslateCTM(context, 0.0f, -size.height);
    CGContextDrawImage(context, myRect, subImage);
    UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(subImage);
    return croppedImage;
}

//选取图片回调
- (void)imagePickerController:(UIImagePickerController *)picker 
didFinishPickingMediaWithInfo:(NSDictionary *)info {
	/*
    UIImage *originalImage = [info objectForKey: UIImagePickerControllerOriginalImage];
    NSLog(@"originalImage(%.0f, %.0f) imageOrientation=%d", originalImage.size.width, originalImage.size.height, originalImage.imageOrientation);
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    NSLog(@"editedImage(%.0f, %.0f)", editedImage.size.width, editedImage.size.height);
    CGRect corpRect = [[info objectForKey:UIImagePickerControllerCropRect] CGRectValue];
    NSLog(@"corpRect(%.0f, %.0f, %.0f, %.0f)", corpRect.origin.x, corpRect.origin.y, corpRect.size.width, corpRect.size.height);

    CGSize size = CGSizeMake(320, 320);
    
    imageView.image = [self cropImage:originalImage to:corpRect andScaleTo:size];
    */
    imageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
	[picker dismissModalViewControllerAnimated:YES];
    upLoadButton.enabled = YES;
}

//取消图片选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissModalViewControllerAnimated:YES];
}

@end
